package com.sdkteam.Database;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

import com.niusounds.sqlite.SQLiteDAO;
import com.sdkteam.Ailatrieuphu.R;
import com.sdkteam.Client.MilMessage;
import com.sdkteam.Client.TCPClient;



public class UpdateDatabase extends ListActivity {

	private TCPClient milClient;
	private MilMessage milMes;
	private SQLiteDAO dao;
	private Button update;
	public String abc;
	JSONObject jObj;
	JSONArray jarr;
	String a, b, c, d, e1, f, g, r;

	ListAdapter adapter;
	ArrayList<HashMap<String, String>> mylist;
	List<Question> list;
	ConnectTask task;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
//		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
//				.detectNetwork() // or .detectAll() for all detectable problems
//				.penaltyDialog() // show a dialog
//				// .permitNetwork() //permit Network access
//				.build());
		
		if (Build.VERSION.SDK_INT > 9) {
			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
			.detectNetwork() // or .detectAll() for all detectable
			// problems
			.penaltyDialog() // show a dialog
			// .permitNetwork() //permit Network access
			.build());
			}
		
		setContentView(R.layout.listplaceholder);

		update = (Button) findViewById(R.id.update);
		mylist = new ArrayList<HashMap<String, String>>();

		jarr = new JSONArray();

		// connect to the server
		task = new ConnectTask();
		task.execute();

		update.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				((BaseAdapter) adapter).notifyDataSetChanged();
				milMes = new MilMessage();
				milMes.OfflineFunctionCode();
				dao = SQLiteDAO.getInstance(getBaseContext(), "Question",
						Question.class);
				dao.delete(Question.class, null, null);

				try {
					milClient.sendMessage(milMes);

				} catch (Exception e1) {
					e1.printStackTrace();
				}

			}
		});

		adapter = new SimpleAdapter(this, mylist, R.layout.main, new String[] {
				"id", "question", "casea", "caseb", "casec", "cased", "result",
				"qLevel" }, new int[] { R.id.item_id, R.id.item_question,
				R.id.item_casea, R.id.item_caseb, R.id.item_casec,
				R.id.item_cased, R.id.item_result, R.id.item_level });

		this.setListAdapter(adapter);

	}

	public void Update(Context context, List<Question> list) {

		Question ques = new Question();
		ques.setQuestion(list.get(0).getQuestion());
		ques.setLevel(list.get(0).getLevel());
		ques.setCasea(list.get(0).getCasea());
		ques.setCaseb(list.get(0).getCaseb());
		ques.setCasec(list.get(0).getCasec());
		ques.setCased(list.get(0).getCased());
		ques.setTrueCase(list.get(0).getTrueCase());

		dao.insert(ques);
	}

	public class ConnectTask extends AsyncTask<Void, MilMessage[], Void> {

		@Override
		protected Void doInBackground(Void... values) {

			// we create a TCPClient object and
			milClient = new TCPClient(new TCPClient.OnMessageReceived() {

				public void messageReceived(MilMessage message) {
					onProgressUpdate(message);
				}
			});
			milClient.run();

			return null;

		}

		protected void onProgressUpdate(MilMessage... values) {

			try {

				jObj = new JSONObject(values[0].getContent());

				jarr = jObj.getJSONArray("l");

				list = new ArrayList<Question>();

				for (int i = 0; i < jarr.length(); i++) {

					JSONObject e = jarr.getJSONObject(i);

					Question ques = new Question();
					ques.setQuestion(e.getString("q"));
					ques.setLevel(Integer.parseInt(e.getString("ql")));
					ques.setCasea(e.getString("qa"));
					ques.setCaseb(e.getString("qb"));
					ques.setCasec(e.getString("qc"));
					ques.setCased(e.getString("qd"));
					ques.setTrueCase(Integer.parseInt(e.getString("r")));
					list.add(ques);
				}
				dao.insertAll(list);
			} catch (JSONException e) {
				e.printStackTrace();
			}

		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(milClient!= null)
		milClient.destroy();
		task.cancel(false);
	}

}